package com.android.job.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.job.fusion.FusionCode;
import com.android.job.fusion.FusionField;
import com.android.job.logic.FileDonwloadLogic;
import com.android.job.logic.UpdateVerLogic;
import com.android.job.model.DownloadItem;
import com.android.job.service.ConnectionTask;
import com.android.job.util.CommonUtil;

/**
 * 主页
 * 
 * @author Administrator
 * 
 */
public class HomeActivity extends BaseActivity implements OnItemClickListener,
		OnClickListener
{

	private GridView gridView;
	private String[] titles;
	private TypedArray icons;
	private static final int DIALOG_UPDATE = 1;
	private static final int DIALOG_EXIT = 2;
	private String url;
	private ProgressDialog pd;
	private TextView login;
	private String testUrl = "http://112.4.128.215:8072/client/employment.apk";
	private SharedPreferences sharedPreferences;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.home);
		gridView = (GridView) findViewById(R.id.home_icons);
		initLayout();
	}

	@Override
	protected void onResume()
	{
		super.onResume();

		if (isLogin())
		{
			login.setText(R.string.logout);
		}
		else
		{
			login.setText(R.string.login);
		}
	}

	private void initLayout()
	{
		pd = new ProgressDialog(HomeActivity.this);
		icons = getResources().obtainTypedArray(R.array.home_icons);

		titles = getResources().getStringArray(R.array.home_item);
		SimpleAdapter simpleAdapter = new SimpleAdapter(this, fillMap(),
				R.layout.griditem, new String[]
				{ "imageView", "imageTitle" }, new int[]
				{ R.id.imageView, R.id.imageTitle });
		// new ColorDrawable(Color.TRANSPARENT)// 选中的时候为透明色
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
//		gridView.setSelector(R.drawable.home_sel);
		gridView.setGravity(Gravity.CENTER);// 位置居中
		gridView.setVerticalSpacing(20);// 垂直间隔
		gridView.setAdapter(simpleAdapter);
		gridView.setOnItemClickListener(this);// 项目点击事件

		login = (TextView) findViewById(R.id.home_login_tv);
		login.setOnClickListener(this);
		// url = testUrl;
//		 update();
		int versionCode = 0;
		try
		{
			versionCode = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		UpdateVerLogic.getInstance().updateVer(handler,String.valueOf(versionCode)  ,"1" );//1为android客户端 2 为ios客户端
		sharedPreferences = getSharedPreferences(FusionField.POSTARR,
				Activity.MODE_PRIVATE);

	}

	public ArrayList<Map<String, Object>> fillMap()
	{
		ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (int i = 0, j = titles.length; i < j; i++)
		{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("imageView", icons.getResourceId(i, 0));
			map.put("imageTitle", titles[i]);
			list.add(map);
		}
		return list;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3)
	{
		Uri content_url;
		Intent intent = new Intent();
		switch (position)
		{
			case FusionCode.ANNOUNCEMENT:
				intent.setAction("android.intent.action.VIEW");
				 content_url = Uri.parse("http://112.4.128.215:8072/news.do?newsTypeId=3");
				intent.setData(content_url);
				startActivity(intent);
				break;
			case FusionCode.APPROVE:
				intent.setAction("android.intent.action.VIEW");
				 content_url = Uri.parse("http://112.4.128.215:8072/news.do?newsTypeId=4");
				intent.setData(content_url);
				startActivity(intent);
				break;
			case FusionCode.CONTACTS:
				intent.setAction("android.intent.action.VIEW");
				 content_url = Uri.parse("http://112.4.128.215:8072/news.do?newsTypeId=1");
				intent.setData(content_url);
				startActivity(intent);
				break;
			case FusionCode.RESUME:
				intent.setClass(this, ResumeActivity.class);
				startActivity(intent);
				break;
			case FusionCode.POSITON:
				intent.setAction("android.intent.action.VIEW");
				content_url = Uri.parse("http://112.4.128.215:8072/news.do?newsTypeId=2");
				intent.setData(content_url);
				startActivity(intent);
				break;
			case FusionCode.JOB:
				intent.setClass(this, JobActivity.class);
				startActivity(intent);
				break;
			case FusionCode.MYFORM:
				intent.setAction("android.intent.action.VIEW");
				content_url = Uri.parse("http://112.4.128.215:8072/news.do?newsTypeId=5");
				intent.setData(content_url);
				startActivity(intent);
				break;
			case FusionCode.MEETTINGROOM:
				intent.setAction("android.intent.action.VIEW");
				content_url = Uri.parse("http://112.4.128.215:8072/news.do?newsTypeId=6");
				intent.setData(content_url);
				startActivity(intent);
				break;
			case FusionCode.LOCATION:
				intent.setClass(this, About.class);
				startActivity(intent);
				break;
				
		}

	}

	private Handler handler = new Handler()
	{

		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case FusionCode.RETURN_JSONOBJECT:
					url = (String) msg.obj;
					update();
					break;

				case FusionCode.SERVER_ERROR:
					pd.dismiss();
					String errorInif = (String) msg.obj;
					
					Toast.makeText(HomeActivity.this,
							errorInif, Toast.LENGTH_SHORT)
							.show();
					break;
			}
		};

	};

	private void update()
	{
		if (url != null && !"".equals(url))
		{
			showDialog(DIALOG_UPDATE);
		}
	}

	private void download(String savePath)
	{
		pd.setTitle("正在加载...");
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.show();
		FileDonwloadLogic.getInstance().downloadUpdateFile(
				FusionField.UPDATE_FILE_NAME, FusionCode.URL_HADE+url, versonHandler, savePath,
				ConnectionTask.GET);
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		switch (id)
		{
			case DIALOG_UPDATE:
				return new AlertDialog.Builder(HomeActivity.this)
						.setTitle(R.string.version_update_msg)
						.setMessage(R.string.version_update)
						.setPositiveButton(R.string.version_update_ok,
								new DialogInterface.OnClickListener()
								{
									public void onClick(DialogInterface dialog,
											int whichButton)
									{
										dialog.dismiss();

										if (CommonUtil.existSDcard())
										{
											download(FusionField.UPDATE_VERSION_SAVEPATH);
										}
										else
										{
											download(FusionField.UPDATE_NOSDCARD_SAVEPATH);
										}

									}
								})
						.setNegativeButton(R.string.version_update_cancel,
								new DialogInterface.OnClickListener()
								{

									@Override
									public void onClick(DialogInterface dialog,
											int which)
									{
										dialog.dismiss();

									}
								}).create();
			case DIALOG_EXIT:
				return new AlertDialog.Builder(HomeActivity.this)
						.setTitle(R.string.app_exit)
						.setMessage(R.string.app_exit_msg)
						.setPositiveButton(R.string.app_exit_ok,
								new DialogInterface.OnClickListener()
								{
									public void onClick(DialogInterface dialog,
											int whichButton)
									{
										dialog.dismiss();
										 logOut();
										finish();
										try
										{
											Runtime.getRuntime()
													.exec("kill -9 "
															+ android.os.Process
																	.myPid());
										}
										catch (IOException e)
										{
											e.printStackTrace();
										}
									}
								})
						.setNegativeButton(R.string.app_exit_cancle,
								new DialogInterface.OnClickListener()
								{

									@Override
									public void onClick(DialogInterface dialog,
											int which)
									{
										dialog.dismiss();

									}
								}).create();

		}
		return super.onCreateDialog(id);
	}

	/**
	 * 版本更新回调句柄
	 */
	private Handler versonHandler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			int what = msg.what;
			switch (what)
			{
				// case FusionCode.VERSION_NO_UPDATE:
				// login();
				// break;
				// case FusionCode.VERSION_HAS_UPDATE:
				// showDialog(DIALOG_UPDATE);
				// break;
				case FusionCode.DOWN_PROCESSING:
					DownloadItem item = (DownloadItem) msg.obj;
					int progress = (int) (item.downLen * 100 / item.fileSize);
					String tip = getString(R.string.version_update_tip);
					pd.setProgress(progress);
					Log.i("free","============progress==========="+progress);
//					pd.setMessage(tip + progress + "%");
					pd.setCancelable(false);
					break;
				case FusionCode.DOWN_SUCCESS:
					pd.dismiss();

					// 判断升级包是否合法
					PackageManager pm = FusionField.currentActivity
							.getPackageManager();
					PackageInfo info = pm.getPackageArchiveInfo(
							FusionField.UPDATE_VERSION_SAVEPATH
									+ FusionField.UPDATE_FILE_NAME,
							PackageManager.GET_ACTIVITIES);
					if (info == null)
					{
						// 不合法
						// showDialog(UPDATE_ERROR);
					}
					else
					{
						// 调用系统安装
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setDataAndType(
								Uri.parse("file://"
										+ FusionField.UPDATE_VERSION_SAVEPATH
										+ FusionField.UPDATE_FILE_NAME),
								"application/vnd.android.package-archive");
						startActivity(intent);
					}
					break;
				case FusionCode.DOWN_FAIL:
				case FusionCode.NETWORK_ERROR:
					pd.dismiss();
					Toast.makeText(HomeActivity.this, R.string.network_error,
							Toast.LENGTH_SHORT).show();
					break;
				case FusionCode.NETWORK_TIMEOUT_ERROR:
					pd.dismiss();
					Toast.makeText(HomeActivity.this, R.string.network_timeout,
							Toast.LENGTH_SHORT).show();
					break;
				case FusionCode.LOW_MEMORY:
					pd.dismiss();
					Toast.makeText(HomeActivity.this,
							R.string.sdcard_low_memory, Toast.LENGTH_SHORT)
							.show();
					break;
				case FusionCode.NO_SDCARD:
					pd.dismiss();
					Toast.makeText(HomeActivity.this, R.string.sdcard_no_exist,
							Toast.LENGTH_SHORT).show();
					break;
				default:
					break;
			}
		}

	};

	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
	{
		if (event.getAction() == KeyEvent.ACTION_DOWN)
		{
			switch (event.getKeyCode())
			{
				case KeyEvent.KEYCODE_BACK:
				{
					showDialog(DIALOG_EXIT);
				}

			}
		}
		return super.dispatchKeyEvent(event);
	}
	
	
	
	
	
	

	@Override
	public void onBackPressed()
	{
		 logOut();
		super.onBackPressed();
	}
	
	private void logOut(){
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.clear();
		editor.commit();
		login.setText(R.string.login);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
			case R.id.home_login_tv:
				
				String loginText = getString(R.string.login);
				String logoutText = getString(R.string.logout);

				if (login.getText().toString().equals(loginText))
				{
					jumpToPage(LoginActivity.class);
				}
				else if (login.getText().toString().equals(logoutText))
				{
					 logOut();
				}

				break;

			default:
				break;
		}
	}
}
